import { Module } from 'vuex'
// login 接口
import {
  accountLoginRequest,
  accountLoginUserInfo,
  accountLoginMenusById
} from '@/service/login/login'
// 定义接口参数类型
import { IAccount } from '@/service/login/types'
// 导入缓存
import localCache from '@/utils/cache'
// 导入路由
import router from '@/router'
// 导入菜单映射路由
import { mapMenusToRoutes } from '@/utils/map-menus'
import { ILoginState } from './types'
import { IRootState } from '../types'
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus

      // userMenus => routes
      const routes = mapMenusToRoutes(userMenus)

      // 将routes=>router.main.children
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
    }
  },
  actions: {
    // 用户登陆逻辑
    async accountLoginAction({ commit }, payload: IAccount) {
      console.log('执行actionloginaction===', payload)
      //   1、实现登陆逻辑
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult.data
      commit('changeToken', token)
      localCache.setCache('token', token)

      // 2、保存用户信息
      const loginUserInfo = await accountLoginUserInfo(id)
      const userInfo = loginUserInfo.data
      commit('changeUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)

      // 3、获取用户菜单
      const loginUserMenus = await accountLoginMenusById(id)
      const userMenus = loginUserMenus.data
      commit('changeUserMenus', userMenus)
      localCache.setCache('userMenus', userMenus)

      // 4、跳转页面
      router.push('/main')
    },
    // 手机号验证码登陆逻辑
    phoneLoginAction({ commit }, payload: any) {
      console.log('执行phoneLoginAction===', payload)
    },
    // 每次刷新进来重新走一遍存放在vuex，防止vuex中的数据被重置为空
    loginResitAction({ commit }) {
      const token = localCache.getCatche('token')
      if (token) {
        commit('changeToken', token)
      }
      const userInfo = localCache.getCatche('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = localCache.getCatche('userMenus')
      if (userMenus) {
        commit('changeUserMenus', userMenus)
      }
    }
  }
}

export default loginModule
